<template>
  <div class="seting-box">
    <s-header :name="'账号管理'"></s-header>
    <div class="input-item">
      <van-field v-model="user.nickName" label="昵称"/>
      <van-field v-model="user.password" type='password' label="修改密码"/>

      <van-cell v-if="userRole==='user'" center title="申请成为商家">
        <template #right-icon>
          <van-switch v-model="beMerchant"/>
        </template>
      </van-cell>
    </div>
    <van-button round class="save-btn" color="#1baeae" type="primary" @click="save" block>保存</van-button>
  </div>
</template>

<script>
import {reactive, onMounted, toRefs} from 'vue'
import sHeader from '@/components/SimpleHeader'
import {getUserInfo, updateUser, updateUserRole} from '@/service/user'
import {removeLocal} from '@/common/js/local-storge'
import {Toast} from 'vant'

export default {
  components: {
    sHeader
  },
  setup() {
    const state = reactive({
      user: {
        password: '',
        nickName: '',
      },
      userRole: '',
      beMerchant: false
    })

    onMounted(async () => {
      const {user, userRole} = await getUserInfo()
      state.user = user
      state.userRole = userRole
    })

    const save = async () => {
      await updateUser({
        "userId": state.user.userId,
        "nickName": state.user.nickName,
        "password": state.user.password,
      })

      if (state.beMerchant) {
        await updateUserRole({
          "roleId": 4
        })
      }

      removeLocal("token")
      Toast.success('保存成功')
      window.location.href = '/'
    }


    return {
      ...toRefs(state),
      save,
    }
  }
}
</script>

<style lang="less" scoped>
.seting-box {
  .save-btn {
    width: 80%;
    margin: 20px auto;
  }
}
</style>
